var toast = require('../../../components/toast/toast.js')
var app = getApp()
var tsCount = 1000;
Page({
    data: {
        carId: '',
        //goDemHide: 'hide',//去办的样式
        notIllegalHide: 'hide',//无违章的样式
        moreHide: 'hide',//查看更多的样式
        btn_loading: false,//点击查看更多按钮的样式
        voliationCount: 0,//违章条数
        fineTotalAmount: 0,//罚款金额
        degreeCount: 0,//扣分

        violations: [],//违章列表
        selectedViolations: [],//已选择的违章列表
        checkAll: false,//是否全选
        FirstcheckAll: true,//第一次是否全选
        sumFineMoney: 0,//已选择的违章罚款总额
        sumPoints: 0,//已选择的违章总扣分
        supplemented: {}//已经补充的资料
    },
    initialization: function () {
        wx.showToast({
            title: '请稍候',
            icon: 'loading',
            duration: 10000,
            mask: true
        });
        this.getIllegalList();
    },
    getIllegalList: function (e) {
        var param = {
            url: '/wx/carViola/getPeccByCarId.ajax',
            para: {
               'carId': this.data.carId,
              'isCanUrgent': true
            }
        };
        let notIllegalHide = this.data.notIllegalHide;

        app.requestSdkForNeedLogin({
            param: param,
            beforeSend: () => {
            
            },
            success: data => {
                if (data.successFlag) {
                    this.getSupplement(); // 获取已经补充的资料

                    let violations = data.data==null?[]:data.data;

                    if (violations.length == 0) {
                        notIllegalHide = "";
                    }

                    for(var i=0;i<violations.length;i++){
                        violations[i].occurTime = app.toYMDHMSDate(violations[i].occurTime)
                    }
                    this.setData({
                        "violations": violations,
                        'notIllegalHide': notIllegalHide
                    })

                } else {
                    wx.hideToast();
                    toast.show(this, data.errormsg)
                }
            },
            complete: data => {
                //   wx.hideToast();
            }
        });
    },
    getSupplement: function () {
        //获取已经补充的资料
        var param = {
            url: '/wx/carViola/selectCarRequirements.ajax',
            para: {
                'carId': this.data.carId
            }
        };

        app.requestSdkForNeedLogin({
            param: param,
            beforeSend: () => {
                //发送请求之前执行
                // wx.showToast({
                //     title: '请稍候',
                //     icon: 'loading',
                //     duration: 10000,
                //     mask: true
                // });
            },
            success: data => {
                  var sign={};
                if (data.successFlag) {
	                for(var key in data.data){
		                if(data.data[key]){
			                sign[key] = data.data[key]
		                }
	                }
                  this.setData({ "supplemented": sign });
                  this.combinationFilter();  // 需要补充的资料

                } else {
                    toast.show(this, data.errormsg)
                }
            },
            complete: data => {
                // setTimeout(function () {
                //     wx.hideToast()
                // }, 500);
            }
        });
    },
    getNeedSupplementByViolation: function () {
        //根据违章获取需要补充的资料
    },
    combinationFilter: function () {
        //筛选出需要补充的资料
        let violations = this.data.violations;  // 需要的数据, 违章列表

        let supplementedItem = this.data.supplemented; // 已有数据

        violations.map(item => {
            if (item.proxyRule) {
                item.proxyRule = JSON.parse(item.proxyRule)
            }
            //console.log("item.proxyRule = ",item.proxyRule);
            let needSupplement = [];

            for (let key in item.proxyRule) {
                if (item.proxyRule.hasOwnProperty(key)) {
                    var element = parseInt(item.proxyRule[key]?item.proxyRule[key]:'0');
                    if (element != 0) {//需要补充的

                      let supplemented = supplementedItem.hasOwnProperty(key) && supplementedItem[key]!='' ;
                        if (supplemented) {
                            if (JSON.parse(item.proxyRule[key]) < 99 && (JSON.parse(item.proxyRule[key]) >supplementedItem[key].length)) {
                                supplemented = false;
                            }
                            else if (JSON.parse(item.proxyRule[key]) == 99 && app.globalData.furtherProperties[key].maxlength == 99 && supplementedItem[key].length < 6) {
                                supplemented = false;
                            }
                        }
                        if (!supplemented) {
                            let info = app.deepClone(app.globalData.furtherProperties[key]); // 默认数据
                            if (info) {
                                needSupplement.push(info);
                            }
                        }
                    }
                }
            }

            item["needSupplement"] = needSupplement;
        });
        // wx.setStorage({ // 异步存储
        //     key: this.data.carId,
        //     data: violations
        // })

        this.setData({
            "violations": violations
        })
        this.checkAll();///第一次全选

        wx.hideToast();
    },
    //点击更多
    addIllegal: function (e) {

    },
    //单选
    checkboxChange: function (e) {
        let values = e.detail.value;
        let violations = this.data.violations;
        let selectedViolations = new Array();
        let checkAll = true;

        let sumFineMoney = 0;
        let sumPoints = 0;

        for (let i = 0; i < violations.length; i++) {
            let item = violations[i];
            item.checked = false;
            for (let j = 0; j < values.length; j++) {
                var violationId = values[j];
                if (violationId == item.violationId) {
                    item.checked = true;
                    sumFineMoney += item.fine;
                    sumPoints += parseInt(item.other);
                    selectedViolations.push(item);
                    break;
                }
            }

            if (item.canProcess == 1) {
                if (!item.checked) {
                    checkAll = false;
                }
            }


        }

        this.setData({
            "checkAll": checkAll,
            "violations": violations,
            "selectedViolations": selectedViolations,
            "sumFineMoney": sumFineMoney,
            "sumPoints": sumPoints
        })
    },

    //全选
    checkAll: function () {

        let checked = !this.data.checkAll;
        let violations = this.data.violations;
        let selectedViolations = new Array();
        let FirstcheckAll = this.data.FirstcheckAll;


        let sumFineMoney = 0;
        let sumPoints = 0;

        violations.map((item, index) => {
            if (item.canProcess == 1) {
                item.checked = checked;
                if (FirstcheckAll) {
                    if (item.other != 0) { //  checked=false; 执行扣分的不选择
                        item.checked = false;
                        checked = false;
                    } else {
                        item.checked = true;
                        sumFineMoney += item.fine;
                        sumPoints += parseInt(item.other);
                        selectedViolations.push(item);
                    }
                }
                else if (checked) {
                    sumFineMoney += item.fine;
                    sumPoints += parseInt(item.other);
                    selectedViolations.push(item);
                }
            }
        });
        if (selectedViolations.length == 0) checked = false;

        this.setData({
            "FirstcheckAll": false,
            "checkAll": checked,
            "violations": violations,
            "selectedViolations": selectedViolations,
            "sumFineMoney": sumFineMoney,
            "sumPoints": sumPoints
        });
    },
    //调转到订单确认页面
    goOrder: function (e) {
        wx.showToast({
            title: '请稍等',
            icon: 'loading',
            duration: 2000
        }); /// toast
        let selectedViolations = this.data.selectedViolations;
        let needSupplement = false;

        let backendIdList = selectedViolations.map(item => {
            return item.backendId
        });

        let violationIdList = selectedViolations.map(item => {
            return item.violationId
        });

        for (var i = 0; i < selectedViolations.length; i++) {
            var item = selectedViolations[i];
            if (item.needSupplement.length > 0) {
                needSupplement = true;
                break;
            }
        }

        if (needSupplement) {
            wx.hideToast(); /// toast
            wx.showModal({
                cancelColor: '#999',
                confirmColor: '#00B488',
                title: '您需要补充资料才能办理',
                success: (res) => {
                    // console.log(res);
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../furtherInfor/furtherInfor?unidList=' + backendIdList + '&carId=' + this.data.carId + '&violationidList=' + violationIdList
                        });
                    } else {
                        wx.hideToast(); /// toast;
                    }
                }
            });

        } else if (selectedViolations.length) {

            wx.navigateTo({
                url: '../determineOrder/determineOrder?unidList=' + violationIdList + '&carId=' + this.data.carId +'&backendIdList='+ backendIdList
            });
        } else {
            toast.show(this, "请选择您要办理的违章", 2500);
            wx.hideToast();
        }

    },
    selectCarInfo: function (e) {
        wx.navigateTo({
            url: '../edit/edit?id=' + this.data.carId
        })
    },
    onLoad: function (options) {
        var carId = options.carId;
        var voliationCount = options.voliationCount;
        var fineTotalAmount = options.fineTotalAmount;
        var degreeCount = options.degreeCount;
        var carNumber = options.carNumber;
        var newCarNumber = carNumber.substring(0, 2) + ' ' + carNumber.substring(2);
        wx.setNavigationBarTitle({ title: newCarNumber }); //标题
    
        if (carId != undefined) {
            this.setData({
                'carId': carId,
                'carNumber': carNumber,
                'voliationCount': voliationCount,
                'fineTotalAmount': fineTotalAmount,
                'degreeCount': degreeCount
            })
        }
    },
    onReady: function () {

    },
    onShow: function () {
        this.setData({
            "checkAll": false
        })
        this.initialization();
    },
    onHide: function () {/////
        this.setData({
            'FirstcheckAll': true
        });
    },
    onShareAppMessage: function () {
        return {
            title: '还在为违章处理排队烦恼吗？',
            desc: '邮证查办违章，免费查询，实时提醒，快速在线缴罚款，车主最贴心的车务管家！ ',
            path: 'pages/carInfo/list/list'
        }
    }
})